// package: rewords-server-2024
// filename: mgx
// author: diogoxiang@gmail.com
// time: 2024/7/31 下午2:46

package mgx

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	field = &Field{
		Id:         "seq",
		Collection: "_id",
	}
)

type Field struct {
	Id         string
	Collection string
}

// SetFieldName 如果不设置，则用默认设置
func SetFieldName(id, collection string) {
	field.Id = id
	field.Collection = collection
}

// AutoInc 使collection 为 name 的 id 自增 1 并返回当前 id 的值
func AutoInc(c *mongo.Collection, name string) (id int, err error) {
	return incr(c, name, 1)
}

// ApplyBatchIds 批量申请一段id
func ApplyBatchIds(c *mongo.Collection, name string, amount int) (id int, err error) {
	return incr(c, name, amount)
}

func incr(c *mongo.Collection, name string, step int) (id int, err error) {
	var (
		//ctx context.Context
		res         *mongo.SingleResult
		findOptions *options.FindOneAndUpdateOptions
	)
	result := make(map[string]interface{})

	findOptions = options.FindOneAndUpdate()
	findOptions.SetUpsert(true)
	findOptions.SetReturnDocument(1)

	res = c.FindOneAndUpdate(context.TODO(), bson.M{field.Collection: name}, bson.M{"$inc": bson.M{field.Id: step}}, findOptions)

	if err = res.Decode(&result); err != nil {
		return 0, err
	}
	//change := qmgo.Change{
	//	Update:    bson.M{"$inc": bson.M{field.Id: step}},
	//	Upsert:    true,
	//	ReturnNew: true,
	//}
	//err = c.Find(ctx, bson.M{field.Collection: name}).Apply(change, result)

	if err != nil {
		return
	}
	id, ok := result[field.Id].(int)
	if ok {
		return
	}
	id32, ok := result[field.Id].(int32)
	if ok {
		id = int(id32)
		return
	}
	id64, ok := result[field.Id].(int64)
	if !ok {
		err = fmt.Errorf("%s is not int or int64", field.Id)
		return
	}
	id = int(id64)
	return
}
